/*
 * Copyright (C) 2011 Mette Bank, Rikke Jensen, Kenneth Brodersen, Thomas Pedersen
 * 
 * This file is part of digiPECS.
 * 
 * digiPECS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * digiPECS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with digiPECS.  If not, see <http://www.gnu.org/licenses/>.
 */

package sw6.digipecs.widget;

import sw6.digipecs.exceptions.NoViewFoundException;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.GridView;

/**
 * Class to override the scroll feature of gridviews
 */
public class ExtImageGridView extends GridView {
	
	private final Rect mRect = new Rect();

	public ExtImageGridView(Context context) {
		super(context);
	}

	public ExtImageGridView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public ExtImageGridView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}
	
	protected View findView(final int x, final int y) throws NoViewFoundException {
		final int count = getChildCount();
		View view;
		final Rect rect = mRect;
		
		for (int i = 0; i < count; i++) {
			view = getChildAt(i);
			view.getHitRect(rect);
			
			if (rect.contains(x, y)) {
				return view;
			}
		}
		
		throw new NoViewFoundException();
	}

	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		try {
			final View view = findView((int)ev.getX(), (int)ev.getY());
			if (view.onTouchEvent(ev)) return true;
		} catch (NoViewFoundException e) { }
		
		return false;
	}

}
